package org.ljy.testdemo.exception;


import lombok.extern.slf4j.Slf4j;
import org.ljy.testdemo.common.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@ResponseBody
@ControllerAdvice
public class ExceptionAdvice {


    @ExceptionHandler(ApplicationException.class)
    public Result applicationExceptionHandler (ApplicationException e) {
        e.printStackTrace();
        // 打印日志
        if (e.getErrorResult() != null) {
            return e.getErrorResult();
        }
        // 一般不会为null，构造方法已经限制住了，但是保险一些
        if (e.getMessage() == null || e.getMessage().equals("")) {
            return Result.fail(e.getMessage());
        }
        // 返回具体的异常信息
        return Result.fail(e.getMessage());
    }

    //兜底捕获异常
    @ExceptionHandler(Exception.class)
    public Result exception(Exception e) {
        log.error(e.getMessage(), e);
        return Result.fail(e.getMessage());
    }
}
